<script lang="ts" setup>
defineOptions({
  name: "HomeScrollSnap",
});

let totalViewData = ref<any>([]);
let firstViewData = ref<any>({});
let remainingViewData = ref<any>([]);
async function fetchHomeData() {
  let resData = await fetchArticleList();
  totalViewData.value = [...totalViewData.value, ...resData.data.rows];
  firstViewData.value = totalViewData.value[0];
  remainingViewData.value = totalViewData.value.slice(1);
  nextTick(() => {
    unobserveAllItems();
    observeAllItems();
    isFixed.value = true;
    scrollEelemntIntoView();
  });
}
import { isEmptyObject } from "@/assets/js/types";
import { ads_ids, bodyRows, DOMAINS, isShowTopUp } from "@/config/ads_ids";
import { pxChangeRem } from "@/utils";
import { set_progress_ratio } from "./store";
import { fetchArticleList } from "@/views/home/store";
import {
  classNameHomeWrapListItem,
  view_home_index,
  classNameHomeScrollSnap,
  classNameHomeListItem,
  classNameActiveScrollParent,
} from "@/config/const_var";
let isFixed = ref(false);
let firstItemRef = ref<any>(null);
let observerFirstItem = new IntersectionObserver((entries) => {
  entries.forEach(async (entry: any) => {
    if (entry.isIntersecting === true) {
      isFixed.value = false;

      SessionStorage.setItem(view_home_index, -1);
    }
    if (entry.isIntersecting === false) {
      isFixed.value = true;
    }
  });
});
function scrollEelemntIntoView() {
  let viewHomeIndex = SessionStorage.getItem(view_home_index);
  if (isEmptyType(viewHomeIndex) || viewHomeIndex * 1 <= 0) {
    firstItemRef.value &&
      firstItemRef.value.scrollIntoView({
        behavior: "instant",
      });
  }
  if (viewHomeIndex * 1 > 0) {
    let homeListItem = itemListRef.value.children[viewHomeIndex - 1];
    homeListItem &&
      homeListItem.scrollIntoView({
        behavior: "instant",
      });
  }
}
let itemListRef = ref<any>(null);
let observerListItem = new IntersectionObserver((entries) => {
  entries.forEach(async (entry: any) => {
    let target = entry.target;
    let index = target.dataset.index * 1;
    if (entry.isIntersecting === true) {
      if (index >= 2) {
        isShowTopUp.value = true;
      } else {
        isShowTopUp.value = false;
      }
      let exposureTimes = target.getAttribute("exposure-times");
      if (isEmptyType(exposureTimes)) {
        target.setAttribute("exposure-times", index);
      }

      SessionStorage.setItem(
        view_home_index,
        target.getAttribute("exposure-times")
      );
      if (!isEmptyType(exposureTimes)) {
        return;
      }
      if (index % (remainingViewData.value.length - 2) === 0 && index != 0) {
        fetchHomeData();
      }
    }
    if (entry.isIntersecting === false) {
    }
  });
});
let homeScrollSnapRef = ref<any>(null);
function handleBodyScrollY(event: { target: any }) {
  let target = event.target;
  let scrollTop = target.scrollTop;
  let clientHeight = firstItemRef.value.clientHeight;
  if (scrollTop >= clientHeight) {
    document.body.style.scrollSnapType = "y mandatory";
  } else {
    document.body.style.scrollSnapType = "none";
  }
  set_progress_ratio(scrollTop, clientHeight);
}
function bindBodyScrollY() {
  document.body.addEventListener("scroll", handleBodyScrollY);
}
function removeBodyScrollY() {
  document.body.removeEventListener("scroll", handleBodyScrollY);
}
function observeAllItems() {
  observerFirstItem.observe(firstItemRef.value);

  [].forEach.call(itemListRef.value.children, (element) => {
    observerListItem.observe(element);
  });
}
function unobserveAllItems() {
  observerFirstItem.unobserve(firstItemRef.value);

  [].forEach.call(itemListRef.value.children, (element) => {
    observerListItem.unobserve(element);
  });
}
function addClassName() {
  firstItemRef.value.classList.add("scroll-active-son");
  itemListRef.value.classList.add(classNameActiveScrollParent);
  document.body.classList.add(classNameActiveScrollParent);
}
onMounted(() => {
  fetchHomeData();
  addClassName();
});
onBeforeRouteLeave(() => {
  removeBodyScrollY();
  unobserveAllItems();
});
let isShowReadMore = ref(true);
let is_show_ads_320_250 = ref(true);
function toggleClassName() {
  document.body.classList.remove(classNameActiveScrollParent);
}

function handleExpand() {
  is_show_ads_320_250.value = false;
  isShowReadMore.value = false;
  firstItemRef.value.style.height = "auto";
  bindBodyScrollY();
  isShowHomeDragUp.value = true;
  isShowDetailAdvert.value = true;
  toggleClassName();
}
let isShowHomeDragUp = ref(false);
let ads_id_320_250 = ref<any>(0);
let hostname = location.hostname;
if (DOMAINS.includes(hostname)) {
  ads_id_320_250.value = ads_ids[hostname]["list_index"]["ads_ids_320_250"][0];
} else {
  ads_id_320_250.value = ads_ids["default_list_index_id"];
}

function getRemainder(number: number) {
  return number % 7;
}
function get_list_index_ads_id_320_100(index: number) {
  if (DOMAINS.includes(hostname)) {
    return ads_ids[hostname]["list_index"]["ads_ids_320_100"][
      getRemainder(index)
    ];
  } else {
    return ads_ids["default_list_index_id"];
  }
}
let isShowDetailAdvert = ref(false);
let ads_320_250_ref = ref<any>(null);
let body_rows = ref(bodyRows.value);
function isEmptyElement(element: { innerHTML: any }) {
  if (element) {
    return isEmptyType(element.innerHTML);
  } else {
    return true;
  }
}
const observerAds = new MutationObserver(function (mutationsList) {
  for (let mutation of mutationsList) {
    let ins: any = mutation.target;
    if (
      mutation.type === "attributes" &&
      mutation.attributeName === "data-ad-status"
    ) {
      let dataAdStatus = ins.getAttribute(mutation.attributeName);
      if (dataAdStatus && dataAdStatus === "unfilled") {
        body_rows.value = bodyRows.value + 4;
      }
      if (dataAdStatus && dataAdStatus === "filled") {
        body_rows.value = bodyRows.value - 3;
      }
    }
    if (isEmptyElement(ins)) {
      ins.parentElement.style.display = "none";
      body_rows.value = bodyRows.value + 4;
    }
  }
});
onMounted(() => {
  if (ads_320_250_ref.value?.$el) {
    let ins = ads_320_250_ref.value?.$el.querySelector(".adsbygoogle");
    observerAds.observe(ins, {
      attributes: true,
    });
  }
});
</script>
<template>
  <div :class="[classNameHomeScrollSnap]" ref="homeScrollSnapRef">
    <div
      :class="[classNameHomeListItem, 'pb-20', 'height-auto-item']"
      ref="firstItemRef"
      :data-index="-1"
    >
      <HomeFirstItem
        v-if="!isEmptyObject(firstViewData)"
        class="pt-16 pl-16 pr-16 pb-16"
        v-model:is-show-read-more="isShowReadMore"
        :content="firstViewData.content"
        :title="firstViewData.title"
        :item="firstViewData"
        :coverImg="firstViewData.coverImg"
        :handleExpand="handleExpand"
        expandText=""
        :is-show-advert="false"
        v-model:is-show-detail-advert="isShowDetailAdvert"
        v-model:bodyRows="body_rows"
        ads_class=""
        :calc_type="1"
      />

      <HomeDragUp class="pl-16 pr-16" v-if="isShowHomeDragUp" />
    </div>

    <Advert
      v-if="DOMAINS.includes(hostname) && is_show_ads_320_250"
      ads_type="0"
      style="height: 250px !important"
      v-model:ads_id="ads_id_320_250"
      ref="ads_320_250_ref"
    />

    <HomeScrollXTabs v-model:is-fixed="isFixed" />

    <div ref="itemListRef" :class="classNameHomeWrapListItem">
      <HomeListItem
        v-for="(item, index) in remainingViewData"
        :key="index"
        :data-index="index"
        :is-show-read-more="false"
        :content="item.content"
        :title="item.title"
        :item="item"
        :coverImg="item.coverImg"
        :style="{
          paddingTop: isFixed ? pxChangeRem('50px') : '0px',
        }"
        class="pl-16 pr-16"
        :is-show-advert="true"
        :ads_type="1"
        :ads_id_320_100="get_list_index_ads_id_320_100(index)"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped>
.#{$scss-classNameHomeScrollSnap} {
  .#{$scss-classNameHomeWrapListItem} {
    &.#{$scss-classNameActiveScrollParent} {
      :deep(.#{$scss-classNameHomeListItem}) {
        height: 80vh;
        scroll-snap-align: start;
        scroll-snap-stop: always;
      }
    }
  }
  .height-auto-item {
    &.scroll-active-son {
      height: 80vh;
      scroll-snap-align: start;
      scroll-snap-stop: always;
    }
  }
}
</style>
